package com.ruoyi.web.controller.wxqy.callback;

import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.cache.Meta;
import com.ruoyi.common.utils.NumberUtils;
import com.ruoyi.common.utils.StrUtils;
import com.ruoyi.qywx.service.inters.TxlCallbackService;
import com.ruoyi.qywx.getway.auth.qywx.WXBizMsgCrypt;
import com.ruoyi.system.service.ISysTeamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

/**
 * @author : hcl
 * @Date : 2023/8/4
 */
@RestController
@RequestMapping("/api/qywx/server")
@Slf4j
public class WxServerCallBackController {

    @Autowired
    private TxlCallbackService callbackService;
    @Autowired
    private ISysTeamService sysTeamService;

    @GetMapping("/consumer/txl/{teamId}")
    public void connectionTxl(HttpServletResponse response,
                              @PathVariable("teamId") Long teamId,
                              String msg_signature,
                              Integer timestamp,
                              String nonce,
                              String echostr) {
        Meta meta = sysTeamService.selectTeamMeta(teamId);
        if (meta != null) {
            WXBizMsgCrypt crypt = new WXBizMsgCrypt(meta.getAppToken(), meta.getAppEncodingAesKey(), meta.getCorpid());
            write(response, crypt.decrypt(echostr));
        } else {
            write(response, StrUtil.EMPTY);
        }
    }

    @PostMapping(value = "/consumer/txl/{teamId}", produces = "application/xml; charset=UTF-8")
    public void consumerTxl(HttpServletResponse response,
                            @PathVariable("teamId") Long teamId,
                            @RequestParam(name = "msg_signature", required = false) String signature,
                            @RequestParam(name = "timestamp", required = false) String timestamp,
                            @RequestParam(name = "nonce", required = false) String nonce,
                            @RequestBody(required = false) String requestBody,
                            @RequestParam(name = "echostr", required = false) String echostr) {

        log.info("prefix=微信服务器响应信息为|nonce={}|timestamp={}|msg_signature={}|xml={}|",
                nonce, timestamp, signature, requestBody);
        if (!NumberUtils.isTrue(teamId)) return;
        Meta meta = sysTeamService.selectTeamMeta(teamId);
        if (meta == null) return;
        WXBizMsgCrypt crypt = new WXBizMsgCrypt(meta.getAppToken(), meta.getAppEncodingAesKey(), meta.getCorpid());
        String xml = crypt.decryptMsg(signature, timestamp, nonce, requestBody);
        log.info("/consumer/txl解密XML: " + xml);
        callbackService.contactChange(xml, meta);
    }

    @GetMapping("/consumer/contact/{teamId}")
    public void connectionContact(HttpServletResponse response,
                                  @PathVariable("teamId") Long teamId,
                                  String msg_signature,
                                  Integer timestamp,
                                  String nonce,
                                  String echostr) {
        Meta meta = sysTeamService.selectTeamMeta(teamId);
        if (meta != null) {
            WXBizMsgCrypt crypt = new WXBizMsgCrypt(meta.getContactTk(), meta.getContactAesk(), meta.getCorpid());
            write(response, crypt.decrypt(echostr));
        } else {
            write(response, StrUtil.EMPTY);
        }
    }

    @PostMapping(value = "/consumer/contact/{teamId}", produces = "application/xml; charset=UTF-8")
    public void consumerContact(HttpServletResponse response,
                                @PathVariable("teamId") Long teamId,
                                @RequestParam(name = "msg_signature", required = false) String signature,
                                @RequestParam(name = "timestamp", required = false) String timestamp,
                                @RequestParam(name = "nonce", required = false) String nonce,
                                @RequestBody(required = false) String requestBody,
                                @RequestParam(name = "echostr", required = false) String echostr) {

        log.info("prefix=客户应信息为|nonce={}|timestamp={}|msg_signature={}|xml={}|",
                nonce, timestamp, signature, requestBody);
        if (!NumberUtils.isTrue(teamId)) return;
        Meta meta = sysTeamService.selectTeamMeta(teamId);
        if (meta == null) return;
        WXBizMsgCrypt crypt = new WXBizMsgCrypt(meta.getContactTk(), meta.getContactAesk(), meta.getCorpid());
        String xml = crypt.decryptMsg(signature, timestamp, nonce, requestBody);
        log.info("/consumer/contact解密XML: " + xml);
        callbackService.externalEvent(xml, meta);
    }

    private void write(HttpServletResponse response, String content) {
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache,no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", -1L);
        try {
            response.getWriter().write(StrUtils.defaultString(content));
            response.getWriter().flush();
            response.setStatus(200);
        } catch (Throwable var5) {
            var5.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String Encrypt = "<xml><ToUserName><![CDATA[wwd938024c1507f101]]></ToUserName><Encrypt><![CDATA[j6MfVjBrKExloe7Agu6dCPXogN02iKYtnHPJz6TkPMcg0ezKoJ0Pv7BT1RtXMfX37pvxVxeFg+v/5ZKObYnMK957tH5SfyYlxYna+cX7tVp5RQkycsp8UKNgwRR6ri2zDHUGRvO5ixopG7gKeuxnSdXicr74Dki+6atyTlTXQoSTLt7xARZJPrkoa0DhjilJJPw7EUlLzDEe2IJ5QOZhJVGCIpmJ/8zdHvQEWUCEgCu8M6kourtlc5dFVm+Cm8kQtcs+fPXf6RVzuY9py21rgB33eDIaRjGvjfNSBg000hB2xk6hoMZKdx7RRHO1iwLP2c2nqMyC7A1ESeYhzdpQSewXJtgXHm7T8aJ73cr3TwpoH+cKbBKl33s5OyZYpr3RSVbHCdHBYqHsn64NMmiXtLlf3gV1883OkF9VZLGmsApkrws1peulcFwVokEiSHYioW0ewjRiGoy1hcWTS24a0A==]]></Encrypt><AgentID><![CDATA[]]></AgentID></xml>";
        WXBizMsgCrypt crypt = new WXBizMsgCrypt("aImqeW",
                "R1OuywAn345rjUWR1zS6bjcKglp8DLYsLLqE4Pg5dXC",
                "wwd938024c1507f101");
        String EncryptStr = crypt.decryptMsg(null, null, null, Encrypt);

        System.out.println(EncryptStr);
        System.out.println(crypt.decryptMsg(null, null, null, EncryptStr));
    }
}
